package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.constants.AdminConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    /**
     * 登录
     *
     * @param adUserDto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto adUserDto) {
        // 参数校验 用户名，密码判空
        if (adUserDto == null || StringUtils.isBlank(adUserDto.getName()) || StringUtils.isBlank(adUserDto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 根据用户名查询，判断，不存在return / throw
        AdUser user = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adUserDto.getName()));
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.ADMIN_USERNAME_NOT_EXIST);
        }
        // 判断账户是否正常，不存在return / throw
        if (user.getStatus() != AdminConstants.ADUSER_NORMAL_STATUS) {
            CustException.cust(AppHttpCodeEnum.ADMIN_USER_NOT_NORMAL);
        }
        // 判断用户密码是否正确
        // 数据库查到的密码
        String password = user.getPassword();
        // 数据库查到的盐
        String salt = user.getSalt();
        // dto未加密的密码
        String dtoPassword = adUserDto.getPassword();
        // dto加密的密码
        String saltPwd = dtoPassword + salt;
        String digestPwd = DigestUtils.md5DigestAsHex(saltPwd.getBytes());
        if (!digestPwd.equals(password)) {
            CustException.cust(AppHttpCodeEnum.ADMIN_PASSWORD_ERROR);
        }
        // 更新最后登录时间 loginTime
        user.setLoginTime(new Date());
        this.updateById(user);
        // 返回前端token
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", AppJwtUtil.getToken(user.getId().longValue()));
        // 置空重要数据
        user.setStatus(null);
        user.setEmail(null);
        user.setPassword(null);
        user.setSalt(null);
        user.setPhone(null);
        map.put("user", user);
        return ResponseResult.okResult(map);
    }

    /**
     * 注册
     *
     * @param adUser
     * @return
     */
    @Override
    public ResponseResult register(AdUser adUser) {
        // 参数校验 用户名密码判空
        if (StringUtils.isBlank(adUser.getName()) || StringUtils.isBlank(adUser.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "用户名或密码不能为空");
        }
        // 用户名判唯一
        if (this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adUser.getName())) != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "用户名已被占用");
        }
        // 生成salt，对密码加密
        String salt = RandomStringUtils.randomAlphanumeric(6);//获取一个6位的随机字符串
        String saltPwd = adUser.getPassword() + salt;
        String md5DigestPwd = DigestUtils.md5DigestAsHex(saltPwd.getBytes());
        // 设置账号状态为正常 9，保存salt，password，创建时间
        adUser.setPassword(md5DigestPwd);
        adUser.setSalt(salt);
        adUser.setStatus(AdminConstants.ADUSER_NORMAL_STATUS);
        adUser.setCreatedTime(new Date());
        // 保存
        this.save(adUser);
        // 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
